<?php

namespace app\common\model\order;

use app\common\model\coupon\Log;
use app\common\model\goods\Goods;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\UserGroup;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'createtime_text',
        'paytime_text',
        'status_text',
        'canceltime_text',
        'taketime_text',
        'pay_type_text',
        'qh_image_str',

    ];

    public function getqhImageStrAttr($value, $data)
    {
        return $data['qh_image'] ? cdnurl($data['qh_image'], true) : '';
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '5' => __('Status 5'), '6' => __('Status 6'), '-1' => __('Status -1')];
    }

    public function getPayTypeList()
    {
        return ['0' => __('Pay_type 0'), '1' => __('Pay_type 1'), '2' => __('Pay_type 2')];
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function shop()
    {
        return $this->belongsTo('app\common\model\Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods()
    {
        return $this->belongsTo('app\common\model\order\Goods', 'id', 'order_id', [], 'INNER')->setEagerlyType(0);
    }
    public function log()
    {
        return $this->belongsTo('app\common\model\coupon\Log', 'coupon_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function moreOrder($array)
    {


        extract($array);
        try {
            //合计金额  //实际支付金额
            $data['total_points'] =  $goods->totalPoint;
            $data['total_money'] =  $goods->totalMoney;
            $data['deduction_money'] =  $pay_money =  $goods->money;
            //优惠金额
            $discount_amount = 0;
            //使用优惠券
            if (isset($coupon_id) && $coupon_id) {
                $discount_amount = Log::useCoupon($data['deduction_money'], $goods, $coupon_id, $uid);
            }
            $data['state'] =  $goods->state;
            $data['coupon_id'] =  $coupon_id ?? 0;
            $data['distribution'] =  $distribution;
            $data['pay_money'] =  bcsub($pay_money, $discount_amount, 2);
            $data['discount_amount'] = bcsub($data['total_money'], $data['pay_money'], 2);
            $data['total'] = $num;
            $addressInfo = [];
            //商家配送取最高运费
            if ($distribution == '1') {
                $freight = $goods->freight;
                if ($freight > 0) {
                    $min = $freight - 5;
                    if ($min <= 0) {
                        $min = 0.01;
                    }
                    $max = $freight + 0.01;
                    $data['freight'] = randomFloat($min, $max);
                } else {
                    $data['freight'] = $freight;
                }
                $data['pay_money'] = bcadd($data['pay_money'], $data['freight'], 2);
                $data['total_money'] = bcadd($data['total_money'],$data['freight'], 2);
            } else {
                $data['shop_id'] = $shop_id;
            }
            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get([$address_id]);
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($uid);
                if ($addressInfo) {
                    $data['addressInfo'] = $addressInfo;
                    $data['address_id']  = $addressInfo['id'];
                }
            }
            $data['goodsList'] = $goods;
            return $data;
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
    public function yuOrder($array)
    {
        extract($array);
        try {
            //合计金额
            $data['total_money'] = array_sum(array_column($goods, 'totalMoney'));
            //实际支付金额
            $pay_money = array_sum(array_column($goods, 'money'));
            $data['deduction_money'] = $pay_money;
            //优惠金额
            $discount_amount = 0;
            //使用优惠券
            if (isset($coupon_id) && $coupon_id) {
                // $coupon = Log::get($coupon_id);
                $discount_amount = Log::useCoupon($data['deduction_money'], array_column($goods, 'goods'), $coupon_id, $uid);
            }
            $data['nowPay'] = 0;
            $data['coupon_id'] =  $coupon_id ?? 0;
            $data['distribution'] =  $distribution;
            $data['pay_money'] =  bcsub($pay_money, $discount_amount, 2);
            $data['discount_amount'] = bcsub($data['total_money'], $data['pay_money'], 2);
            $data['total'] = array_sum(array_column($goods, 'num'));
            $addressInfo = [];
            //商家配送取最高运费
            if ($distribution == '1') {
                $freight = max(array_column(array_column($goods, 'goods'), 'freight'));
                if ($freight > 0) {
                    $min = $freight - 5;
                    if ($min <= 0) {
                        $min = 0.01;
                    }
                    $max = $freight + 0.01;
                    $data['freight'] = mt_rand($min, $max);
                } else {
                    $data['freight'] = $freight;
                }
                $data['pay_money'] = bcadd($data['pay_money'], $data['freight'], 2);
                $data['total_money'] = bcadd($data['total_money'], $data['freight'], 2);
            } else {
                $data['shop_id'] = $shop_id;
            }

            //地址信息
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get([$address_id]);
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($uid);
                if ($addressInfo) {
                    $data['addressInfo'] = $addressInfo;
                    $data['address_id']  = $addressInfo['id'];
                }
            }
            $data['goodsList'] = $goods;
            cache('order_' . $uid, $data, '900');
            return $data;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
    public  function addData($data,  $uid)
    {
        $list = $data['goodsList'];
        $addressInfo = [];
        if ($data['addressInfo']) {
            $addressInfo = $data['addressInfo'];
        }
        $userInfo = User::get($uid);
        if ($userInfo->group_id > $list['level'] && $list['category_id'] == 23) {
            exception('当前等级大于购买等级');
        }
        if ($userInfo->group_id == 1) {
            $p_id = $userInfo->pid;
            $p_interests = $list['p_interests'];
        } else {
            $p_id = $p_interests = 0;
        }
        $array = [
            'user_id' => $uid,
            'total_money' =>  $data['total_money'],
            'total_points' =>  $data['total_points'],
            'total' =>  $data['total'],
            'state' =>  $data['state'],
            'pay_money' =>  $data['pay_money'],
            'freight' =>  $data['freight'] ?? 0,
            'discount_amount' =>  $data['discount_amount'],
            'sn' => sn('order', 'sn', 'NO'),
            'address_id' => $data['address_id'],
            'distribution' => $data['distribution'],
            'coupon_id' => $data['coupon_id'],
            'shop_id' => $data['shop_id'] ?? 0,
            'city' => $addressInfo['city'] ?? '',
            'consignee' => $addressInfo['contact'] ?? '',
            'phone' => $addressInfo['telephone'] ?? '',
            'address' => $addressInfo['address'],
            'interests' => bcmul($list['interests'], $data['total'], 0),
            'dividend' => bcmul($list['dividend'], $data['total'], 2),
            'p_id' => $p_id,
            'p_interests' => $p_interests,
            'group_id' => $list['level'],
        ];

        $res = $this->allowField(true)->save($array);
        if ($res) {
            $info = [
                'order_id' => $this->id,
                'goods_id' => $list['id'],
                'category_id' => $list['category_id'],
                'goods_num' => $data['total'],
                'goods_name' => $list['title'],
                'goods_price' => $list['price'],
                'total_price' => $list['price'] * $data['total'],
                'image' => $list['image'],
            ];
            $infos = new OrderGoods();
            $infos->isUpdate(false)->save($info);
        }
        return $this->id;
    }
}
